package com.yonyougov.devops.cruxcisupport.k8s.log;

import com.yonyougov.devops.cruxcisupport.k8s.K8sRepository;
import com.yonyougov.devops.cruxcisupport.k8s.error.K8sConfIgNotFindException;
import com.yonyougov.devops.cruxcisupport.k8s.error.PodNotFindException;
import com.yonyougov.devops.cruxcisupport.k8s.error.PodNotReadyException;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.client.KubernetesClient;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.stream.Collectors;

@Repository
public class LoggerRepositoryImpl implements LoggerRepository {
    private final K8sRepository k8sRepository;

    public LoggerRepositoryImpl(K8sRepository k8sRepository) {
        this.k8sRepository = k8sRepository;
    }

    @Override
    public String getPodLog(String nameSpace, String podName, int seconds) throws K8sConfIgNotFindException, PodNotFindException, PodNotReadyException {
        KubernetesClient client = k8sRepository.createDefaultClient(nameSpace);
        //获取容器名称
        Pod pod = client.pods().inNamespace(nameSpace).withName(podName).get();
        if(null == pod){
            throw new PodNotFindException("根据 "+ podName + "找不到pod,检查是否部署");
        }
        Boolean isReady = pod.getStatus().getContainerStatuses().get(0).getReady();
        if(isReady){
            return client.pods().inNamespace(nameSpace).withName(podName).sinceSeconds(seconds).getLog();

        }else{
            throw new PodNotReadyException(podName + "还没有启动就绪");
        }
    }

    @Override
    public String getPodLogByTail(String nameSpace, String podName, int tails) throws K8sConfIgNotFindException, PodNotFindException, PodNotReadyException {
        KubernetesClient client = k8sRepository.createDefaultClient(nameSpace);
        //获取容器名称
        Pod pod = client.pods().inNamespace(nameSpace).withName(podName).get();
        if(null == pod){
            throw new PodNotFindException("根据 "+ podName + "找不到pod,检查是否部署");
        }
        Boolean ready = pod.getStatus().getContainerStatuses().get(0).getReady();
        if(ready){
            return client.pods().inNamespace(nameSpace).withName(podName).tailingLines(tails).getLog();

        }else{
            throw new PodNotReadyException(podName + "还没有启动就绪");
        }
    }
}
